package pemks.dao;

import pemks.entity.User;

import java.sql.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import pemks.util.DBUtil;
import pemks.util.PasswordUtil;

/**
 * @description:  
 * @author kl
 * @date 2025/4/4 下午9:29
 * @version 1.0
 */
public class UserDAO {

    public boolean register(User user) throws SQLException {
        String sql = "INSERT INTO users (username, password, pk_g1, pk_g2, pk_h, role) " +
                "VALUES (?, ?, ?, ?, ?, ?)";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, user.getUsername());
//            stmt.setString(2, encodePassword(user.getPassword()));
            stmt.setString(2, user.getPassword());
            stmt.setString(3, user.getPkG1());
            stmt.setString(4, user.getPkG2());
            stmt.setString(5, user.getPkH());
            stmt.setString(6, user.getRole());

            return stmt.executeUpdate() > 0;
        }
    }

    public User findByUsername(String username) throws SQLException {
        String sql = "SELECT * FROM users WHERE username = ?";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, username);
            ResultSet rs = stmt.executeQuery();

            if (rs.next()) {
                User user = new User();
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setPkG1(rs.getString("pk_g1"));
                user.setPkG2(rs.getString("pk_g2"));
                user.setPkH(rs.getString("pk_h"));
                user.setRole(rs.getString("role"));
                return user;
            }
            return null;
        }
    }

    public List<User> getAllUsers() {
        String sql = "SELECT username,password FROM users";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            List<User> users = new ArrayList<>();
            ResultSet rs = stmt.executeQuery();

            while (rs.next()) {
                User user = new User();
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                users.add(user);
            }
            return users;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public boolean validatePassword(String rawPassword, String encodedPassword) {
        return rawPassword.equals(encodedPassword);
//        return PasswordUtil.matches(rawPassword, encodedPassword);
    }

    private String encodePassword(String rawPassword) {
        return PasswordUtil.encode(rawPassword);
    }
}
